package com.nf.health.app;

import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.nf.health.app.db.DbManager;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by fei on 2016/4/14.
 */
public class AppModel {
    private static AppModel appModel;
    public static AppModel getInstatnce(){
        if(appModel == null){
            appModel = new AppModel();
        }
        return appModel;
    }
    private AppModel(){};

    Map<String, EaseUser> contactList;

    public Map<String, EaseUser> getContactList(){
        if (EMClient.getInstance().isLoggedInBefore() &&  contactList == null) {
            contactList = DbManager.getInstance().getContactList();
        }
        if(contactList == null){
            contactList = new HashMap<>();
        }
        return contactList;
    }

    /**
     * 保存单个user
     */
    public void saveContact(EaseUser user){
        if(!contactList.containsKey(user.getUsername())){
            contactList.put(user.getUsername(), user);
            DbManager.getInstance().saveContact(user);
        }else {
            if(!contactList.get(user.getUsername()).getNick().equals(user.getUsername())
                    || !contactList.get(user.getUsername()).getAvatar().equals(user.getAvatar())){
                contactList.remove(user.getUsername());
                contactList.put(user.getUsername(), user);
                DbManager.getInstance().saveContact(user);
            }
        }
    }
}
